package org.rainwalk.bill.controller;


import cn.hutool.crypto.digest.BCrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.rainwalk.bill.api.interceptor.AuthInterceptor;
import org.rainwalk.bill.api.log.ApiLog;
import org.rainwalk.bill.api.model.Response;
import org.rainwalk.bill.api.model.ResponseCode;
import org.rainwalk.bill.api.model.SessionUser;
import org.rainwalk.bill.entity.AppUser;
import org.rainwalk.bill.model.dto.PasswordUpdateDTO;
import org.rainwalk.bill.service.IAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 趁雨行
 * @since 2021-02-18
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/app-user")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class AppUserController {

    private final IAppUserService appUserService;

    @ApiLog("更改密码")
    @ApiOperation(value = "更改密码")
    @PutMapping
    public Response updatePassword(@RequestBody @Validated PasswordUpdateDTO dto, @SessionAttribute(AuthInterceptor.USER_SESSION) SessionUser sessionUser) {
        AppUser user = appUserService.getById(sessionUser.getId());
        if (!BCrypt.checkpw(dto.getOldPassword(), user.getPassword())) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "密码错误");
        }
        AppUser appUser = new AppUser();
        appUser.setId(sessionUser.getId());
        appUser.setPassword(BCrypt.hashpw(dto.getNewPassword()));
        this.appUserService.updateById(appUser);
        return Response.success();
    }

}
